<?php

require_once 'Pipes/FileSystem/Helper/Finder.php';
require_once 'Pipes/FileSystem/Helper/Loader.php';
require_once 'Pipes/FileSystem/View/Finder.php';
require_once 'Pipes/View/Result.php';
require_once 'Pipes/Namespace/Parser.php';
require_once 'PipesImpl/Namespace/Parser.php';
require_once 'Pipes/Form/Factory.php';
require_once 'PipesImpl/View.php';

class Pipes_View implements PipesImpl_View
{
    private $_config = null;
    private $_corral = array();
    private $_namespace = null;
    private $_name = null;
    private $_path = '';

    private $_finder = null;
    private $_helperLoader = null;
    
    public function __construct(PipesImpl_Config $config, $path)
    {
        $this->_config = $config;
        $this->_finder = new Pipes_FileSystem_View_Finder($config, $path);

        $this->_helperLoader = new Pipes_FileSystem_Helper_Loader(
            new Pipes_FileSystem_Helper_Finder($this->_config)
        );
    }
    public function __set($key, $value) {
        $this->_corral[$key] = $value;
    }
    
    public function __get($key) {
        return $this->_corral[$key];
    }

    public function __isset($key) {
        return isset($this->_corral[$key]);
    }
    
    public function __call($method, $arguments)
    {
        $this->_helperLoader->load(ucfirst(strtolower($method)));
        $helperName = $this->_helperLoader->lastLoaded;
        
        $helper = new $helperName($this->_config, $this);
        return call_user_func_array(array($helper, 'factory'), $arguments);
    }
    
    public function setName($name) {
        $this->_name = $name;
    }
    
    public function render($name = null) {
        if (!is_null($name)) {
            $this->setName($name);
        }
        
        ob_start();
        $file = $this->_finder->find($this->_name);
        require $file->fullPath;
        $return = ob_get_clean();
        return new Pipes_View_Result($return);
    }
}

